
import axios from "axios";
import qs from 'qs';
import config from "@/common/config.js";


// 创建实例
var service = axios.create({
  baseURL: config.baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  } 
});

/*
 *请求前拦截
 *用于处理需要请求前的操作
 */
service.interceptors.request.use(
  config => {
    // var token = cookie.get('userToken');
    // if (token) {
    //   config.headers["TOKEN"] = token;
    // }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
/*
 *请求响应拦截
 *用于处理数据返回后的操作
 */
service.interceptors.response.use(
  response => {
    return new Promise((resolve, reject) => {
      const res = response.data;
      if (res.code === 200) {
        resolve(res)
      // token过期
      } else if (res.code == 401 || res.code == 403) {
        // Message.error('用户登陆过期，请重新登陆');
        // logout();
      } else{
        // Message.error(res.msg);
        reject(res)
      }
    })
  },
  error => {
    //断网处理或者请求超时
    if (!error.response) {
      //请求超时
      if (error.message.includes("timeout")) {
        // Message.error('请求超时，请检查互联网连接');
      } else {
        //断网，可以展示断网组件
        // Message.error('请检查网络是否已连接');
      }
      return;
    }
    const status = error.response.status;
    // Message.error(error.response.data.message);
    return Promise.reject(error);
  }
);

const http = {
  baseURL: config.baseURL
}

// 添加get请求
http.get = (url, param = {}, header = {}) => {
  return service({
    url,
    method: 'get',
    params: param,
    headers: header,
    withCredentials:true,   //允许跨域携带cookit
  })
}

// 添加post请求
http.post = (url, param = {}, header = {}) => {
  return service({
    url,
    method: 'post',
    data: param,
    headers: header,
    withCredentials:true,   //允许跨域携带cookit
  });
}

// 表单类型提交
http.form = (url, param = {}, header = {}) => {
  return vm.$post(url, qs.stringify(param), {
    'Content-Type': 'application/x-www-form-urlencoded'
  });
}

// 增加patch请求
http.patch = (url, params = {}, header = {}) => {
  return service({
    url,
    method: 'PATCH',
    data: param,
    withCredentials:true,   //允许跨域携带cookit
  })
}

export default http;